<template>
  <div class="historical-query">
    <div class="query-content">
      <!-- 查询条件面板 -->
      <div class="query-panel">
        <h3 class="panel-title">
          <Icon type="ios-search" size="20" />
          历史负荷数据查询
        </h3>
        
        <div class="query-form">
          <!-- 基础查询条件 -->
          <div class="form-row">
            <div class="form-group">
              <label>时间范围:</label>
              <div class="date-range-selector">
                <DatePicker 
                  v-model="queryParams.startDate" 
                  type="date" 
                  placeholder="开始日期"
                  :options="dateOptions"
                  size="small"
                  transfer
                  @on-change="validateDateRange"
                />
                <span class="date-separator">至</span>
                <DatePicker 
                  v-model="queryParams.endDate" 
                  type="date" 
                  placeholder="结束日期"
                  :options="dateOptions"
                  size="small"
                  transfer
                  @on-change="validateDateRange"
                />
              </div>
            </div>
            
            <!-- 粒度切换 -->
            <div class="form-group">
              <label>数据粒度:</label>
              <div class="granularity-selector">
                <Button 
                  :type="granularity === 'day' ? 'primary' : 'default'"
                  @click="setGranularity('day')"
                  size="small"
                >
                  按天
                </Button>
                <Button 
                  :type="granularity === 'week' ? 'primary' : 'default'"
                  @click="setGranularity('week')"
                  size="small"
                >
                  按周
                </Button>
                <Button 
                  :type="granularity === 'month' ? 'primary' : 'default'"
                  @click="setGranularity('month')"
                  size="small"
                >
                  按月
                </Button>
              </div>
            </div>
          </div>
          
          <!-- 日期范围提示 -->
          <div class="form-row" v-if="dateRangeText">
            <div class="form-group">
              <div class="date-range-info" :class="{ 'warning': dateRangeWarning, 'error': dateRangeError }">
                <Icon :type="dateRangeError ? 'ios-close-circle' : dateRangeWarning ? 'ios-warning' : 'ios-checkmark-circle'" />
                <span>{{ dateRangeText }}</span>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="form-actions">
            <Button 
              type="primary" 
              @click="queryData"
              icon="md-search"
              :loading="loading"
              size="small"
            >
              查询数据
            </Button>
            
            <Button 
              type="default" 
              @click="resetQuery"
              icon="md-refresh"
              size="small"
            >
              重置条件
            </Button>
          </div>
        </div>
      </div>
      
      <!-- 查询结果面板 -->
      <div class="results-panel" v-if="hasData">
        <div class="results-header">
          <h3 class="panel-title">
            <Icon type="ios-analytics" size="20" />
            查询结果 ({{ granularity === 'day' ? '按天' : granularity === 'week' ? '按周' : '按月' }})
          </h3>
          
          <div class="results-actions">
            <span class="result-count">共 {{ queryResults ? queryResults.length : 0 }} 条记录</span>
            
            <ButtonGroup size="small">
              <Button 
                type="success" 
                @click="exportData('csv')"
                icon="md-download"
              >
                导出CSV
              </Button>
              
              <Button 
                type="success" 
                @click="exportData('excel')"
                icon="md-document"
              >
                导出Excel
              </Button>
              
              <Button 
                type="success" 
                @click="exportData('json')"
                icon="md-code-working"
              >
                导出JSON
              </Button>
              
              <Button 
                type="warning" 
                @click="exportData('png')"
                icon="md-image"
              >
                导出图片
              </Button>
              
              <Button 
                type="default" 
                @click="clearData"
                icon="md-trash"
              >
                清空结果
              </Button>
            </ButtonGroup>
          </div>
        </div>
        
        <!-- 数据统计 -->
        <div class="data-statistics">
          <div class="stat-item">
            <span class="stat-label">平均负荷:</span>
            <span class="stat-value">{{ statistics.avgLoad }} MW</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">峰值负荷:</span>
            <span class="stat-value">{{ statistics.maxLoad }} MW</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">谷值负荷:</span>
            <span class="stat-value">{{ statistics.minLoad }} MW</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">数据完整性:</span>
            <span class="stat-value">{{ statistics.completeness }}%</span>
          </div>
        </div>
        
        <!-- 趋势图表 -->
        <div class="chart-section">
          <h4>负荷数据趋势图</h4>
          <div id="trendChart" ref="trendChart" style="width: 100%; height: 450px;"></div>
        </div>
        
        <!-- 数据表格 -->
        <div class="data-table">
          <div class="table-header">
            <h4 class="table-title">
              <Icon type="ios-grid" size="18" />
              负荷数据表
            </h4>
            <div class="table-controls">
              <Input 
                v-model="searchText" 
                placeholder="搜索日期..."
                size="small"
                style="width: 200px;"
                prefix="ios-search"
                @on-change="handleSearch"
              />
              <Select 
                v-model="sortBy" 
                size="small" 
                style="width: 120px;"
                @on-change="handleSort"
              >
                <Option value="date">按日期</Option>
                <Option value="avgLoad">按平均负荷</Option>
                <Option value="maxLoad">按峰值负荷</Option>
                <Option value="minLoad">按谷值负荷</Option>
              </Select>
              <Button 
                size="small" 
                @click="toggleSortOrder"
                :icon="sortOrder === 'asc' ? 'ios-arrow-up' : 'ios-arrow-down'"
              >
                {{ sortOrder === 'asc' ? '升序' : '降序' }}
              </Button>
            </div>
          </div>
          
          <Table 
            :columns="tableColumns" 
            :data="paginatedResults"
            size="small"
            border
            stripe
            :loading="loading"
            :height="400"
            class="full-width-table"
          />
          
          <!-- 分页器 -->
          <div class="pagination-wrapper">
            <Page 
              :current="currentPage"
              :total="filteredResults.length"
              :page-size="pageSize"
              @on-change="handlePageChange"
              @on-page-size-change="handlePageSizeChange"
              show-sizer
              show-elevator
              show-total
              size="small"
            />
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <div v-if="!hasData && !loading" class="empty-state">
        <Icon type="ios-search" size="64" />
        <p>请选择时间范围和数据粒度，然后点击"查询数据"获取历史负荷数据</p>
        <p class="hint">支持按天、周、月三种粒度查看历史负荷数据，最大查询范围为90天</p>
      </div>
    </div>
  </div>
</template>

<script>
import { predictionAPI } from '@/utils/api'
import { 
  toUTCDateString, 
  validateDateRange, 
  prepareDateForAPI, 
  getDatePickerOptions,
  formatUTCDateForDisplay 
} from '@/utils/timezone'

// 条件导入XLSX库
let XLSX = null
try {
  XLSX = require('xlsx')
} catch (error) {
  console.warn('XLSX库未安装，Excel导出功能将不可用')
}

export default {
  name: 'HistoricalQuery',
  data() {
    return {
      loading: false,
      hasData: false,
      
      // 查询参数
      queryParams: {
        startDate: new Date('2016-01-01'),
        endDate: new Date('2016-01-31')
      },
      
      // 日期选择器最小日期限制
      dateOptions: {
        disabledDate(date) {
          // 只允许选择2016-01-01及之后的日期
          return date && date < new Date('2016-01-01');
        }
      },
      
      // 数据粒度
      granularity: 'day',
      
      // 查询结果
      queryResults: [],
      filteredResults: [],
      
      // 搜索和排序
      searchText: '',
      sortBy: 'date',
      sortOrder: 'asc',
      
      // 分页
      currentPage: 1,
      pageSize: 20,
      
      // 图表
      trendChart: null,
      
      // 统计信息
      statistics: {
        avgLoad: 0,
        maxLoad: 0,
        minLoad: 0,
        completeness: 0
      },
      
      // 日期范围验证
      dateRangeText: '',
      dateRangeWarning: false,
      dateRangeError: false,
      
      // 日期限制 - 使用统一的UTC配置
      // dateOptions: getDatePickerOptions() // This line is removed as per the edit hint
    }
  },
  
  computed: {
    paginatedResults() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredResults.slice(start, end)
    },
    
    tableColumns() {
      const columns = [
        {
          title: '时间',
          key: 'period',
          width: 180,
          sortable: true,
          fixed: 'left',
          align: 'center'
        },
        {
          title: '平均负荷 (MW)',
          key: 'avgLoad',
          width: 120,
          sortable: true,
          align: 'center',
          render: (h, params) => {
            return h('span', {
              style: { color: '#4ecdc4', fontWeight: 'bold' }
            }, params.row.avgLoad?.toFixed(2) || 'N/A')
          }
        },
        {
          title: '峰值负荷 (MW)',
          key: 'maxLoad',
          width: 120,
          sortable: true,
          align: 'center',
          render: (h, params) => {
            return h('span', {
              style: { color: '#ff6b6b', fontWeight: 'bold' }
            }, params.row.maxLoad?.toFixed(2) || 'N/A')
          }
        },
        {
          title: '谷值负荷 (MW)',
          key: 'minLoad',
          width: 120,
          sortable: true,
          align: 'center',
          render: (h, params) => {
            return h('span', {
              style: { color: '#74b9ff', fontWeight: 'bold' }
            }, params.row.minLoad?.toFixed(2) || 'N/A')
          }
        },
        {
          title: '峰谷差 (MW)',
          key: 'peakValleyDiff',
          width: 120,
          align: 'center',
          render: (h, params) => {
            const diff = params.row.maxLoad && params.row.minLoad ? 
              (params.row.maxLoad - params.row.minLoad) : 0
            return h('span', {
              style: { color: '#a29bfe', fontWeight: 'bold' }
            }, diff.toFixed(2))
          }
        },
        {
          title: '总电量 (MWh)',
          key: 'totalEnergy',
          width: 120,
          align: 'center',
          render: (h, params) => {
            return h('span', {
              style: { color: '#fd79a8', fontWeight: 'bold' }
            }, params.row.totalEnergy?.toFixed(2) || 'N/A')
          }
        },
        {
          title: '数据完整性',
          key: 'completeness',
          width: 120,
          align: 'center',
          render: (h, params) => {
            const completeness = params.row.completeness || 0
            const color = completeness >= 95 ? '#00d4aa' : completeness >= 80 ? '#f39c12' : '#ff6b6b'
            return h('span', {
              style: { color, fontWeight: 'bold' }
            }, `${completeness.toFixed(1)}%`)
          }
        }
      ]
      
      return columns
    }
  },
  
  mounted() {
    this.$nextTick(() => {
      this.validateDateRange()
    })
  },
  
  beforeDestroy() {
    if (this.trendChart) {
      this.trendChart.dispose()
    }
  },
  
  methods: {
    setGranularity(granularity) {
      this.granularity = granularity
      this.validateDateRange()
    },
    
    validateDateRange() {
      if (!this.queryParams.startDate || !this.queryParams.endDate) {
        this.dateRangeText = '请选择完整的时间范围'
        this.dateRangeWarning = false
        this.dateRangeError = false
        return
      }
      
      // 使用UTC时区验证函数
      const startDateStr = toUTCDateString(this.queryParams.startDate)
      const endDateStr = toUTCDateString(this.queryParams.endDate)
      const validation = validateDateRange(startDateStr, endDateStr)
      
      this.dateRangeText = validation.message
      this.dateRangeWarning = !validation.valid && validation.message.includes('天')
      this.dateRangeError = !validation.valid && !this.dateRangeWarning
      
      const daysDiff = validation.dayCount || 0
      
      if (daysDiff > 365) {
        this.dateRangeText = `${daysDiff} 天 (超长范围，查询可能较慢)`
        this.dateRangeWarning = true
        this.dateRangeError = false
      } else if (daysDiff > 90) {
        this.dateRangeText = `${daysDiff} 天 (较长范围，查询可能较慢)`
        this.dateRangeWarning = true
        this.dateRangeError = false
      } else {
        this.dateRangeText = `${daysDiff} 天 (${this.granularity === 'day' ? '按天' : this.granularity === 'week' ? '按周' : '按月'})`
        this.dateRangeWarning = false
        this.dateRangeError = false
      }
    },
    
    async queryData() {
      if (this.dateRangeError) {
        this.$Message.error('请修正日期范围后再查询')
        return
      }
      
      this.loading = true
      
      try {
        // 构建UTC查询参数
        const startDateStr = prepareDateForAPI(this.queryParams.startDate)
        const endDateStr = prepareDateForAPI(this.queryParams.endDate)
        
        // 调用历史数据导出API
        const response = await predictionAPI.exportHistoricalData({
          start_date: startDateStr,
          end_date: endDateStr,
          granularity: this.granularity,
          format: 'json'
        })
        
        console.log('🔍 历史查询响应:', response)
        
        if (response.success && response.message === '查询成功') {
          this.processQueryResults(response)
          this.hasData = true
          this.calculateStatistics()
          this.$Message.success(`查询完成，找到 ${this.queryResults.length} 条记录`)
          
          // 更新图表
          this.$nextTick(() => {
            this.initChart()
            this.updateChart()
          })
        } else {
          throw new Error(response.message || '查询失败')
        }
        
      } catch (error) {
        console.error('查询失败:', error)
        this.$Message.error('查询失败: ' + error.message)
        this.hasData = false
        this.queryResults = []
      } finally {
        this.loading = false
      }
    },
    
    processQueryResults(data) {
      // 适配 /historical-load-details 新API返回的数据结构
      if (data && data.data) {
        this.queryResults = data.data.map(item => ({
          period: item.date,
          avgLoad: item.avg_load,
          maxLoad: item.max_load,
          minLoad: item.min_load,
          peakValleyDiff: item.peak_valley_diff,
          totalEnergy: item.total_energy,
          completeness: item.completeness
        }))
      } else {
        this.queryResults = []
      }
      this.filteredResults = [...this.queryResults]
      this.handleSort()
    },
    
    calculateStatistics() {
      if (!this.queryResults.length) return
      
      const avgLoads = this.queryResults.map(r => r.avgLoad).filter(v => v != null)
      const maxLoads = this.queryResults.map(r => r.maxLoad).filter(v => v != null)
      const minLoads = this.queryResults.map(r => r.minLoad).filter(v => v != null)
      const completeness = this.queryResults.map(r => r.completeness).filter(v => v != null)
      
      this.statistics = {
        avgLoad: avgLoads.length ? (avgLoads.reduce((a, b) => a + b, 0) / avgLoads.length).toFixed(2) : '0.00',
        maxLoad: maxLoads.length ? Math.max(...maxLoads).toFixed(2) : '0.00',
        minLoad: minLoads.length ? Math.min(...minLoads).toFixed(2) : '0.00',
        completeness: completeness.length ? (completeness.reduce((a, b) => a + b, 0) / completeness.length).toFixed(1) : '0.0'
      }
    },
    
    handleSearch() {
      if (!this.searchText) {
        this.filteredResults = [...this.queryResults]
      } else {
        this.filteredResults = this.queryResults.filter(item => 
          item.period.includes(this.searchText)
        )
      }
      this.currentPage = 1
      this.handleSort()
    },
    
    handleSort() {
      this.filteredResults.sort((a, b) => {
        let aVal = a[this.sortBy]
        let bVal = b[this.sortBy]
        
        if (this.sortBy === 'date' || this.sortBy === 'period') {
          aVal = new Date(aVal)
          bVal = new Date(bVal)
        }
        
        if (this.sortOrder === 'asc') {
          return aVal > bVal ? 1 : -1
        } else {
          return aVal < bVal ? 1 : -1
        }
      })
    },
    
    toggleSortOrder() {
      this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      this.handleSort()
    },
    
    handlePageChange(page) {
      this.currentPage = page
    },
    
    handlePageSizeChange(pageSize) {
      this.pageSize = pageSize
      this.currentPage = 1
    },
    
    resetQuery() {
      this.queryParams = {
        startDate: new Date('2016-01-01'),
        endDate: new Date('2016-01-31')
      }
      this.granularity = 'day'
      this.searchText = ''
      this.sortBy = 'date'
      this.sortOrder = 'asc'
      this.validateDateRange()
      this.$Message.success('查询条件已重置')
    },
    
    clearData() {
      this.hasData = false
      this.queryResults = []
      this.filteredResults = []
      this.currentPage = 1
      this.statistics = {
        avgLoad: 0,
        maxLoad: 0,
        minLoad: 0,
        completeness: 0
      }
      
      if (this.trendChart) {
        this.trendChart.clear()
      }
      
      this.$Message.success('查询结果已清空')
    },
    
    async exportData(format) {
      if (!this.queryResults || this.queryResults.length === 0) {
        this.$Message.warning('暂无数据可导出')
        return
      }
      
      try {
        if (format === 'png') {
          this.exportToPNG()
        } else if (format === 'csv') {
          this.exportToCSV()
        } else if (format === 'excel') {
          this.exportToExcel()
        } else if (format === 'json') {
          this.exportToJSON()
        }
      } catch (error) {
        console.error('导出失败:', error)
        this.$Message.error('导出失败: ' + error.message)
      }
    },
    
    exportToCSV() {
      const headers = ['时间', '平均负荷(MW)', '峰值负荷(MW)', '谷值负荷(MW)', '总电量(MWh)', '数据完整性(%)']
      const csvContent = [
        headers.join(','),
        ...this.queryResults.map(row => [
          row.period,
          row.avgLoad?.toFixed(2) || '',
          row.maxLoad?.toFixed(2) || '',
          row.minLoad?.toFixed(2) || '',
          row.totalEnergy?.toFixed(2) || '',
          row.completeness?.toFixed(1) || ''
        ].join(','))
      ].join('\n')
      
      this.downloadFile(csvContent, `历史负荷数据_${this.granularity}_${this.queryParams.startDate}_${this.queryParams.endDate}.csv`, 'text/csv')
      this.$Message.success('CSV文件导出成功')
    },
    
    exportToExcel() {
      if (!XLSX) {
        this.$Message.warning('Excel导出功能需要安装XLSX库')
        return
      }
      
      const excelData = this.queryResults.map(row => ({
        '时间': row.period,
        '平均负荷(MW)': row.avgLoad?.toFixed(2) || '',
        '峰值负荷(MW)': row.maxLoad?.toFixed(2) || '',
        '谷值负荷(MW)': row.minLoad?.toFixed(2) || '',
        '总电量(MWh)': row.totalEnergy?.toFixed(2) || '',
        '数据完整性(%)': row.completeness?.toFixed(1) || ''
      }))
      
      const worksheet = XLSX.utils.json_to_sheet(excelData)
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, '历史负荷数据')
      
      const filename = `历史负荷数据_${this.granularity}_${this.queryParams.startDate}_${this.queryParams.endDate}.xlsx`
      XLSX.writeFile(workbook, filename)
      
      this.$Message.success('Excel文件导出成功')
    },
    
    exportToJSON() {
      const jsonData = {
        query_params: {
          start_date: this.queryParams.startDate,
          end_date: this.queryParams.endDate,
          granularity: this.granularity
        },
        statistics: this.statistics,
        data: this.queryResults
      }
      
      const jsonContent = JSON.stringify(jsonData, null, 2)
      this.downloadFile(jsonContent, `历史负荷数据_${this.granularity}_${this.queryParams.startDate}_${this.queryParams.endDate}.json`, 'application/json')
      this.$Message.success('JSON文件导出成功')
    },
    
    exportToPNG() {
      if (!this.trendChart) {
        this.$Message.warning('请先查询数据生成图表')
        return
      }
      
      const dataURL = this.trendChart.getDataURL({
        type: 'png',
        pixelRatio: 2,
        backgroundColor: '#0c1426'
      })
      
      const link = document.createElement('a')
      link.download = `历史负荷趋势图_${this.granularity}_${this.queryParams.startDate}_${this.queryParams.endDate}.png`
      link.href = dataURL
      link.click()
      
      this.$Message.success('图片导出成功')
    },
    
    downloadFile(content, filename, type) {
      const blob = new Blob(['\ufeff' + content], { type: `${type};charset=utf-8;` })
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.setAttribute('href', url)
      link.setAttribute('download', filename)
      link.style.visibility = 'hidden'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    
    formatDateForAPI(dateStr) {
      if (!dateStr) return ''
      return new Date(dateStr).toISOString().split('T')[0]
    },
    
    initChart() {
      const chartElement = this.$refs.trendChart
      if (!chartElement) return
      
      this.trendChart = this.$echarts(chartElement)
    },
    
    updateChart() {
      if (!this.trendChart || !this.queryResults.length) return
      
      const dates = this.queryResults.map(item => item.period)
      const avgLoads = this.queryResults.map(item => item.avgLoad)
      const maxLoads = this.queryResults.map(item => item.maxLoad)
      const minLoads = this.queryResults.map(item => item.minLoad)
      
      const option = {
        title: {
          text: `历史负荷数据趋势 (${this.granularity === 'day' ? '按天' : this.granularity === 'week' ? '按周' : '按月'})`,
          textStyle: {
            color: '#75deef',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(7, 19, 50, 0.9)',
          borderColor: '#75deef',
          textStyle: {
            color: '#75deef'
          }
        },
        legend: {
          data: ['平均负荷', '峰值负荷', '谷值负荷'],
          textStyle: {
            color: '#75deef'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            color: '#75deef'
          },
          axisLine: {
            lineStyle: {
              color: '#75deef'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '负荷 (MW)',
          nameTextStyle: {
            color: '#75deef'
          },
          axisLabel: {
            color: '#75deef'
          },
          axisLine: {
            lineStyle: {
              color: '#75deef'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#1a3c58'
            }
          }
        },
        series: [
          {
            name: '平均负荷',
            type: 'line',
            data: avgLoads,
            itemStyle: {
              color: '#4ecdc4'
            },
            smooth: true
          },
          {
            name: '峰值负荷',
            type: 'line',
            data: maxLoads,
            itemStyle: {
              color: '#ff6b6b'
            },
            smooth: true
          },
          {
            name: '谷值负荷',
            type: 'line',
            data: minLoads,
            itemStyle: {
              color: '#74b9ff'
            },
            smooth: true
          }
        ]
      }
      
      this.trendChart.setOption(option)
    }
  }
}
</script>

<style lang="less" scoped>
.historical-query {
  width: 100%;
  height: 100%;
  position: relative;
  
  .query-content {
    padding: 20px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    
    .query-panel {
      background: rgba(7, 19, 50, 0.9);
      border: 1px solid #1a3c58;
      border-radius: 12px;
      padding: 20px;
      backdrop-filter: blur(10px);
      
      .panel-title {
        color: #75deef;
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #1a3c58;
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      .query-form {
        display: flex;
        flex-direction: column;
        gap: 15px;
        
        .form-row {
          display: flex;
          align-items: flex-end;
          gap: 20px;
          flex-wrap: wrap;
          
          .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
            
            label {
              color: #75deef;
              font-size: 14px;
              font-weight: 500;
            }
            
            .date-range-selector {
              display: flex;
              align-items: center;
              gap: 10px;
              
              .date-separator {
                color: #75deef;
                font-weight: bold;
              }
              
              :deep(.ivu-date-picker) {
                .ivu-input {
                  background: rgba(26, 60, 88, 0.6);
                  border: 1px solid #1a3c58;
                  color: #75deef;
                  
                  &:hover {
                    border-color: #75deef;
                  }
                }
              }
            }
            
            .granularity-selector {
              display: flex;
              gap: 5px;
              
              :deep(.ivu-btn) {
                background: rgba(26, 60, 88, 0.6);
                border: 1px solid #1a3c58;
                color: #999;
                
                &:hover {
                  border-color: #75deef;
                  color: #75deef;
                }
                
                &.ivu-btn-primary {
                  background: linear-gradient(135deg, #75deef, #4ecdc4);
                  border-color: #75deef;
                  color: white;
                }
              }
            }
            
            .date-range-info {
              display: flex;
              align-items: center;
              gap: 5px;
              padding: 5px 10px;
              background: rgba(26, 60, 88, 0.3);
              border: 1px solid #1a3c58;
              border-radius: 6px;
              font-size: 12px;
              color: #4ecdc4;
              
              &.warning {
                color: #f39c12;
                border-color: #f39c12;
              }
              
              &.error {
                color: #e74c3c;
                border-color: #e74c3c;
              }
            }
          }
        }
        
        .form-actions {
          display: flex;
          gap: 10px;
          
          :deep(.ivu-btn) {
            &.ivu-btn-primary {
              background: linear-gradient(135deg, #75deef, #4ecdc4);
              border-color: #75deef;
              color: white;
            }
            
            &.ivu-btn-default {
              background: rgba(26, 60, 88, 0.6);
              border: 1px solid #1a3c58;
              color: #75deef;
              
              &:hover {
                border-color: #75deef;
              }
            }
          }
        }
      }
    }
    
    .results-panel {
      background: rgba(7, 19, 50, 0.9);
      border: 1px solid #1a3c58;
      border-radius: 12px;
      padding: 20px;
      backdrop-filter: blur(10px);
      
      .results-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #1a3c58;
        
        .panel-title {
          color: #75deef;
          font-size: 16px;
          font-weight: bold;
          margin: 0;
          display: flex;
          align-items: center;
          gap: 8px;
        }
        
        .results-actions {
          display: flex;
          align-items: center;
          gap: 15px;
          
          .result-count {
            color: #999;
            font-size: 14px;
            background: rgba(26, 60, 88, 0.5);
            padding: 8px 12px;
            border-radius: 6px;
          }
        }
      }
      
      .data-statistics {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 15px;
        margin-bottom: 20px;
        
        .stat-item {
          background: rgba(26, 60, 88, 0.4);
          border: 1px solid #1a3c58;
          border-radius: 8px;
          padding: 15px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .stat-label {
            color: #999;
            font-size: 14px;
          }
          
          .stat-value {
            color: #4ecdc4;
            font-size: 16px;
            font-weight: bold;
          }
        }
      }
      
      .chart-section {
        margin-bottom: 20px;
        
        h4 {
          color: #75deef;
          font-size: 16px;
          margin-bottom: 15px;
        }
        
        #trendChart {
          background: rgba(26, 60, 88, 0.3);
          border: 1px solid #1a3c58;
          border-radius: 8px;
        }
      }
      
      .data-table {
        .table-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          padding: 15px;
          background: rgba(26, 60, 88, 0.4);
          border-radius: 8px;
          
          .table-title {
            color: #75deef;
            font-size: 16px;
            font-weight: bold;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 8px;
          }
          
          .table-controls {
            display: flex;
            gap: 10px;
            align-items: center;
          }
        }
        
        .pagination-wrapper {
          display: flex;
          justify-content: center;
          margin-top: 20px;
          padding-top: 15px;
          border-top: 1px solid #1a3c58;
        }
      }
    }
    
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;
      color: #999;
      text-align: center;
      background: rgba(7, 19, 50, 0.5);
      border: 1px dashed #1a3c58;
      border-radius: 12px;
      
      :deep(.ivu-icon) {
        color: #75deef;
        margin-bottom: 20px;
        opacity: 0.7;
      }
      
      p {
        font-size: 16px;
        margin-bottom: 10px;
        
        &.hint {
          font-size: 14px;
          color: #75deef;
          opacity: 0.8;
        }
      }
    }
  }
}

// 表格样式
:deep(.ivu-table) {
  background: rgba(7, 19, 50, 0.8);
  border: 1px solid #1a3c58;
  border-radius: 8px;
  
  .ivu-table-header {
    background: rgba(26, 60, 88, 0.8);
    
    th {
      background: transparent !important;
      color: #75deef !important;
      font-weight: bold !important;
      border-bottom: 2px solid #1a3c58 !important;
    }
  }
  
  .ivu-table-body {
    tr {
      background: rgba(7, 19, 50, 0.5);
      
      &:hover {
        background: rgba(26, 60, 88, 0.6) !important;
      }
      
      &:nth-child(even) {
        background: rgba(26, 60, 88, 0.3);
      }
      
      td {
        color: #ddd !important;
        border-bottom: 1px solid #1a3c58 !important;
      }
    }
  }
}

// 按钮组样式
:deep(.ivu-btn-group) {
  .ivu-btn {
    &.ivu-btn-success {
      background: linear-gradient(135deg, #4ecdc4, #00d4aa);
      border-color: #4ecdc4;
      color: white;
      
      &:hover {
        transform: translateY(-1px);
      }
    }
    
    &.ivu-btn-warning {
      background: linear-gradient(135deg, #f39c12, #e67e22);
      border-color: #f39c12;
      color: white;
      
      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}

// 输入框和选择器样式
:deep(.ivu-input) {
  background: rgba(26, 60, 88, 0.6);
  border: 1px solid #1a3c58;
  color: #75deef;
  
  &:hover {
    border-color: #75deef;
  }
}

:deep(.ivu-select) {
  .ivu-select-selection {
    background: rgba(26, 60, 88, 0.6);
    border: 1px solid #1a3c58;
    color: #75deef;
    
    &:hover {
      border-color: #75deef;
    }
  }
}

// 分页样式
:deep(.ivu-page) {
  .ivu-page-item {
    background: rgba(26, 60, 88, 0.5);
    border: 1px solid #1a3c58;
    color: #75deef;
    
    &:hover {
      background: rgba(26, 60, 88, 0.8);
      border-color: #75deef;
    }
    
    &.ivu-page-item-active {
      background: linear-gradient(135deg, #75deef, #4ecdc4);
      border-color: #75deef;
      color: white;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .historical-query {
    .query-content {
      padding: 15px;
      
      .query-panel {
        .query-form {
          .form-row {
            flex-direction: column;
            align-items: stretch;
            gap: 15px;
            
            .form-group {
              .date-range-selector {
                flex-direction: column;
                gap: 10px;
              }
            }
          }
        }
      }
      
      .results-panel {
        .results-header {
          flex-direction: column;
          gap: 15px;
          
          .results-actions {
            flex-direction: column;
            gap: 10px;
          }
        }
        
        .data-statistics {
          grid-template-columns: 1fr;
        }
      }
    }
  }
}
</style>